<?php
/**
 * 中控接口类
 *   2017-04-10         http://woaaphub.etocrm.com
 *   2017-04-13 更新：   http://woaapapi.etocrm.com
 */
namespace App\Libs;

use Illuminate\Support\Facades\Redis;
use Ixudra\Curl\Facades\Curl;

class WoaapClient
{
    private static $DOMAIN_URL = 'http://woaapapi.etocrm.com';
    private static $APPKEY = 'e108740ebe575882d8e0ecdb8fe73043'; // 2017年6月8日12:59:47
    //private static $APPKEY = '0f5c8c845370a3fbb564bf44c04ae0f1'; // 新给的
    private static $APPID = 'wx4ed9e1f4e0f3eeb0';


    /**
     * 获取ack
     * @param $openid
     * @return mixed
     */
    public static function getAckey($openid)
    {
        /*$redis_ack = Redis::get($openid.'_ack');
        if ($redis_ack) {
            return $redis_ack;
        }*/
        $url = self::$DOMAIN_URL.'/api/ackey?appid='.self::$APPID.'&appkey='.self::$APPKEY;
        $res = fun_curl_get($url);
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            Redis::set($openid.'_ack', $res['ackey']);
            return $res['ackey'];
        }
        fun_respon(0, '获取Ackey错误');

    }

    /**
     * 获取Access——token
     * @param $ack
     * @return mixed
     */
    public static function getAccessToken($ack)
    {
        $url = self::$DOMAIN_URL.'/api/accesstoken?ackey='.$ack;
        $res =  Curl::to( $url)->get();
        var_dump($ack);
        var_dump($res);die;
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            return $res['access_token'];
        }
        fun_respon(0, '获取access_token错误');
    }

    /**
     * 获取unionid
     * @param $ack
     * @param $openid
     * @return mixed
     */
    public static function getUnionid($ack, $openid)
    {
        $url = self::$DOMAIN_URL.'/api/userinfo?ackey='.$ack.'&openid='.$openid.'&lang=zh_CN';
        $res =  Curl::to( $url)->get();
        $res = json_decode($res, true);
        if (!isset($res['unionid'])) {
            fun_respon(0, '获取unionid错误');
        }
        return $res;
    }

    /**
     * 输出unionid
     */
    public static function returnUnionid($openid)
    {
        $ack = self::getAckey($openid);
        $res = self::getUnionid($ack, $openid);
        if (!isset($res['unionid'])) {
            fun_respon(0, '获取信息错误');
        }
        return $res['unionid'];
    }


    
}